package com.threeti.mecool.core.domain.model.plan.pojo;

import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.JsonToken;
import org.codehaus.jackson.map.DeserializationContext;
import org.codehaus.jackson.map.deser.std.StdScalarDeserializer;

import java.io.IOException;
import java.sql.Time;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * <p/>
 * zhaoxu @ 2012-06-08 09:49
 * <p/>
 */
public class SqlTimeDeserializer extends StdScalarDeserializer<Time> {
    public static final String TIME_FORMAT = "HH:mm:ss";

    public SqlTimeDeserializer() {
        super(Time.class);
    }

    @Override
    public Time deserialize(JsonParser jp, DeserializationContext context) throws IOException {
        Date d = _parseTime(jp, context);
        return (d == null) ? null : new Time(d.getTime());
    }

    protected Date _parseTime(JsonParser jp, DeserializationContext context) throws IOException {
        JsonToken t = jp.getCurrentToken();
        if (t == JsonToken.VALUE_NUMBER_INT) {
            return new Date(jp.getLongValue());
        } else if (t == JsonToken.VALUE_NULL) {
            return getNullValue();
        } else if (t == JsonToken.VALUE_STRING) {
            try {
                String str = jp.getText().trim();
                if (str.length() == 0) {
                    return getEmptyValue();
                }
                return new SimpleDateFormat(TIME_FORMAT).parse(str);
            } catch (Exception iae) {
                throw context.weirdStringException(_valueClass, "not a valid representation (error: " + iae.getMessage() + ")");
            }
        } else {
            throw context.mappingException(_valueClass, t);
        }
    }
}
